const express = require("express");
const router = express.Router();

const { Comment, User, Article } = require("../../models");
const { Op } = require("sequelize");
const { success, failure } = require('../../utils/responses');

/**
 *查询所有评论
 * GET /admin/comments 
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;

    // 当前第几页
    const currentPage = Math.abs(Number(query.currentPage)) || 1;

    // 每页多少条数据
    const pageSize = Math.abs(Number(query.pageSize)) || 10;

    const offset = (currentPage - 1) * pageSize;

    const condition = {
      order: [["id", "DESC"]],
      limit: pageSize,
      offset: offset,
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'nickname', 'avatar'],
        }
      ]
    };

    // 如果有内容搜索
    if (query.content) {
      condition.where = {
        content: {
          [Op.like]: `%${query.content}%`,
        },
      };
    }

    // 如果按文章ID筛选
    if (query.articleId) {
      condition.where = {
        ...condition.where,
        articleId: query.articleId
      };
    }

    // 如果按用户ID筛选
    if (query.userId) {
      condition.where = {
        ...condition.where,
        userId: query.userId
      };
    }

    const { count, rows } = await Comment.findAndCountAll(condition);
    success(res, "查询评论列表成功", {
      comments: rows,
      pagination: {
        total: count,
        currentPage,
        pageSize,
      },
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 新增评论
 * POST /admin/comments
 */
router.post("/", async function (req, res) {
  try {
    const comment = await Comment.create(filterBody(req));
    success(res, "新增评论成功", comment);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除评论
 * DELETE /admin/comments/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const comment = await Comment.findByPk(req.params.id);
    if (!comment) {
      return failure(res, "评论不存在");
    }
    await comment.destroy();
    success(res, "删除评论成功");
  } catch (error) {
    failure(res, error);
  }
});

/** 
 * 白名单过滤
*/
function filterBody(req) {
  return {
    content: req.body.content,
    userId: req.body.userId,
    articleId: req.body.articleId,
  };
}

module.exports = router;